package com.ruoyi.delivery.controller;

import com.ruoyi.delivery.domain.DelDriver;
import com.ruoyi.delivery.domain.dto.MiniDelivery;
import com.ruoyi.delivery.service.IDelDeliveryBatchService;
import com.ruoyi.delivery.service.IDelDriverService;
import com.ruoyi.delivery.utils.OpenidUtils;
import com.ruoyi.framework.web.service.TokenService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Objects;

@RestController
@RequestMapping("/delivery/wechat")
public class DelWechatController {

    private final IDelDeliveryBatchService deliveryBatchService;
    private final TokenService tokenService;
    private final IDelDriverService driverService;
    private final OpenidUtils openidUtils;

    public DelWechatController(IDelDeliveryBatchService deliveryBatchService, TokenService tokenService, IDelDriverService driverService, OpenidUtils openidUtils) {
        this.deliveryBatchService = deliveryBatchService;
        this.tokenService = tokenService;
        this.driverService = driverService;
        this.openidUtils = openidUtils;
    }

    /**
     * 根据微信用户的司机编号获取配送单批次信息
     *
     * @param driverId 司机编号
     * @return 配送单批次信息
     */
    @GetMapping("/getDeliveryOrderBatch")
    public ResponseEntity<MiniDelivery> getDeliveryOrderBatch(@RequestAttribute("openid") String openid) {
        DelDriver driver = driverService.getDriverByOpenId(openid);
        if(driver == null) {
            return ResponseEntity.status(401).body(null);
        } else {
            return ResponseEntity.ok(deliveryBatchService.getDeliveryOrderBatch(driver.getDriverNo()));
        }
    }

    @GetMapping("/token")
    public ResponseEntity<String> getToken(@RequestParam String code) {

        try {
            String openid = openidUtils.getOpenid(code);

            // 写一个方法 根据openid获取司机id和信息，如果没有的话要求用户填写他自己的信息再写到对应的司机的数据里
            DelDriver driver = driverService.getDriverByOpenId(openid);
            if (driver == null) {
                return ResponseEntity.status(401).body("请先绑定司机信息");
            }

            String token = Jwts.builder()
                    .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000))
                    .setSubject(openid)
                    .signWith(SignatureAlgorithm.HS256, tokenService.getSecret())
                    .compact();

            return ResponseEntity.ok(token);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseEntity.status(500).body("获取token失败");

    }

    //    wx.request({
//        url: `http://localhost:8080/delivery/wechat/validate?jobName=${jobName}&name=${name}`,
    @GetMapping("/validate")
    public ResponseEntity<String> validate(@RequestParam String jobNumber, @RequestParam String name, @RequestParam String code) {
        DelDriver driver = driverService.getDriverInfo(jobNumber);
        // 第一种 不存在该工号
        if(driver == null) {
            return ResponseEntity.status(401).body("账号不存在");
        // 第二种 该工号已经绑定
        }else if (Objects.equals(driver.getWechatState(), "已注册")) {
            return ResponseEntity.status(401).body("该账号已被绑定");
        // 第三种 该工号未绑定
        }else if (driverService.validateDriverNameById(jobNumber, name)) {
            String openid = openidUtils.getOpenid(code);
            driverService.updateDriverOpenId(jobNumber, openid);
            String token = Jwts.builder()
                    .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000))
                    .setSubject(openid)
                    .signWith(SignatureAlgorithm.HS256, tokenService.getSecret())
                    .compact();
            return ResponseEntity.ok(token);
        } else {
            return ResponseEntity.status(401).body("信息填写有误");
        }
    }
}
